const mongoose = require("mongoose")

//新增商品

const addGoods = async (goods) => {

    return await mongoose.model('shop-goods').create(goods);
}
// 获取商品
const getGoods = async ({ curPage = 1, eachPage = 3 }) => {

    const result = {
        curPage: ~~curPage,
        eachPage: ~~eachPage,
        total: 0,
        maxPage: 0,
        rows: []
    }
    const goodsModel = mongoose.model("shop-goods")
    result.total = await goodsModel.countDocuments();
    result.maxPage = Math.ceil(result.total / result.eachPage)
    result.rows = await goodsModel
        .find()
        .skip((result.curPage - 1) * result.eachPage)
        .limit(result.eachPage)
        .exec()
    return result
}

//更新商品
const update = async (goods) =>
    await mongoose.model('shop-goods')
        .findByIdAndUpdate(goods._id, {
            name: goods.name,
            price: goods.price,
            goodsNum: goods.goodsNum,
            production: goods.production,
            shelfLife: goods.shelfLife,
            producer: goods.producer,
            weight: goods.weight,
            desc: goods.desc,
            type: goods.type,
            kind: goods.kind,
            discount: goods.discount,
        }, (err, ret) => {
            data = err ? console.log("失败", err) : console.log('成功');
        });
//删除电影
const deleteGoods = async (_id = {}) =>
    await mongoose.model('shop-goods').deleteOne({ _id }, (err, ret) => {
        if (err) {
            console.log("删除失败");
        } else {
            console.log("删除成功");
        }
    })
//通过name获取查询商品
const serchGoods = async ({ serName }) => {
    return await mongoose.model('shop-goods').find({
        name: {
            $regex: String(serName)
        },
    })
}
// 修改图片
const updataImgs = async (_id, images) =>
    await mongoose.model('shop-goods')
        .findByIdAndUpdate(_id, {
            images: images
        }, (err, ret) => {
            data = err ? console.log("失败", err) : console.log('成功');
        });
module.exports = { addGoods, getGoods, update, deleteGoods, serchGoods, updataImgs }

